package com.icloud.cer.rest.util;

import com.icloud.cer.rest.Constants;
import com.icloud.cer.rest.msg.MessageHeader;
import com.icloud.cer.rest.msg.MessageHolder;
import com.icloud.cer.rest.msg.MsgConstants;
import com.icloud.cer.rest.msg.bean.EncryptRequest;
import com.icloud.cer.rest.msg.bean.HeartbeatRequest;
import com.icloud.cer.rest.msg.bean.HeartbeatResponse;

public class MessageUtils {

	public static MessageHolder getEncryptRequestHolder(String userId,String certification) {
		MessageHolder requestHolder = new MessageHolder(MsgConstants.SERVER_SENT_ENCRYPT);
		MessageHeader header = getHeader(EncryptRequest.BYTE_COUNT, MsgConstants.SERVER_SENT_ENCRYPT);
		requestHolder.setHead(header);
		
//		long sequence = MessageSequenceGenerator.getNextMessageId();
		EncryptRequest er = new EncryptRequest();
		er.setUserId(userId);
		er.setCertification(certification);
		//er.setSequence(sequence);
		er.setTaskId(1l);//FIXME 目前一次性就只请求一个任务
		requestHolder.setValue(er);
		
		return requestHolder;
	}
	
	public static MessageHolder getHeartbeatResponse() {
		MessageHolder holder = new MessageHolder(MsgConstants.CLIENT_RES_HEARTBEAT);
		MessageHeader head = new MessageHeader();
		head.setSize_(8);
		head.setType_(MsgConstants.CLIENT_RES_HEARTBEAT);
		head.setFlag_(Constants.DEFAULT_CODEC_FLAG);
		
		long seq = MessageSequenceGenerator.getNextMessageId();
		HeartbeatResponse hb = new HeartbeatResponse();
		hb.setSequence(seq);
		
		holder.setHead(head);
		holder.setValue(hb);
		holder.setSequence(seq);
		return holder;
		
	}
	
	/**
	 * 请求加密机状态时sequence为非0，正常心跳包sequence设置为0。
	 * @return
	 */
	public static MessageHolder getHeartbeatRequestForStatus() {
		MessageHolder requestHolder = new MessageHolder(MsgConstants.SERVER_REQ_HEARTBEAT);
		MessageHeader header = getHeader(HeartbeatRequest.BYTE_COUNT, MsgConstants.SERVER_REQ_HEARTBEAT);
		requestHolder.setHead(header);
		
		HeartbeatRequest hr = new HeartbeatRequest();
		requestHolder.setValue(hr);
		
		return requestHolder;
	}
	
	/**
	 * 正常心跳包sequence设置为0，请求加密机状态时sequence为非0
	 * @return
	 */
	public static MessageHolder getHeartbeatRequest() {
		MessageHolder holder = new MessageHolder(MsgConstants.SERVER_REQ_HEARTBEAT);
		MessageHeader head = new MessageHeader();
		head.setSize_(8);
		head.setType_(MsgConstants.SERVER_REQ_HEARTBEAT);
		head.setFlag_(Constants.DEFAULT_CODEC_FLAG);
		
		long seq = 0;//正常心跳包sequence设置为0，请求加密机状态时sequence为非0
		HeartbeatRequest hb = new HeartbeatRequest();
		hb.setSequence(seq);
		
		holder.setHead(head);
		holder.setValue(hb);
		holder.setSequence(seq);
		return holder;
	}
	
	public static MessageHeader getHeader(int size, short cmd) {
		MessageHeader header = new MessageHeader();
		header.setType_(cmd);
		header.setFlag_(Constants.DEFAULT_CODEC_FLAG);
		header.setSize_(size);
		return header;
	}
}
